package com.springcloud.store.modular.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springcloud.commom.api.ResultCode;
import com.springcloud.commom.exception.ServiceException;
import com.springcloud.commom.factory.PageFactory;
import com.springcloud.commom.page.PageResult;
import com.springcloud.stock.entity.Product;
import com.springcloud.stock.param.ProductParam;
import com.springcloud.store.modular.product.mapper.ProductMapper;
import com.springcloud.store.modular.product.service.ProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品表service接口实现类
 *
 * @author hzl
 * @date 2024-07-26 10:42:06
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Override
    public PageResult<Product> page(ProductParam productParam) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(productParam)) {

            // 根据商品名称 查询
            if (ObjectUtil.isNotEmpty(productParam.getName())) {
                queryWrapper.lambda().eq(Product::getName, productParam.getName());
            }
            // 根据商品数量 查询
            if (ObjectUtil.isNotEmpty(productParam.getProductCount())) {
                queryWrapper.lambda().eq(Product::getProductCount, productParam.getProductCount());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<Product> list(ProductParam productParam) {
        return this.list();
    }

    @Override
    public void add(ProductParam productParam) {
        Product product = new Product();
        BeanUtil.copyProperties(productParam, product);
        this.save(product);

        int i = 1/0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(ProductParam productParam) {
        this.removeById(productParam.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ProductParam productParam) {
        Product product = this.queryProduct(productParam);
        BeanUtil.copyProperties(productParam, product);
        this.updateById(product);
    }

    @Override
    public Product detail(ProductParam productParam) {
        return this.queryProduct(productParam);
    }

    /**
     * 获取商品表
     *
     * @author hzl
     * @date 2024-07-26 10:42:06
     */
    private Product queryProduct(ProductParam productParam) {
        Product product = this.getById(productParam.getId());
        if (ObjectUtil.isNull(product)) {
            throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR);
        }
        return product;
    }
}
